package com.ruoyi.system.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;

import com.alibaba.fastjson2.JSON;
import com.donghu.openapiclientsdk.client.OpenApiClient;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.InterfaceInfoStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.InterfaceInfo;
import com.ruoyi.system.domain.InterfaceInfoInvokeRequest;
import com.ruoyi.system.service.IInterfaceInfoService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.IUserInterfaceInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 【请填写功能名称】Controller
 *
 * @author ruoyi
 * @date 2023-02-26
 */
@RestController
@Anonymous
@RequestMapping("/system/info")
public class InterfaceInfoController extends BaseController {
    @Autowired
    private IInterfaceInfoService interfaceInfoService;
    @Autowired
    private OpenApiClient openApiClient;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IUserInterfaceInfoService userInterfaceInfoService;


    /**
     * 查询【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('system:info:list')")
    @GetMapping("/list")
    public TableDataInfo list(InterfaceInfo interfaceInfo) {
        startPage();
        List<InterfaceInfo> list = interfaceInfoService.selectInterfaceInfoList(interfaceInfo);
        String username = SecurityUtils.getUsername();
        return getDataTable(list);
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('system:info:export')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, InterfaceInfo interfaceInfo) {
        List<InterfaceInfo> list = interfaceInfoService.selectInterfaceInfoList(interfaceInfo);
        ExcelUtil<InterfaceInfo> util = new ExcelUtil<InterfaceInfo>(InterfaceInfo.class);
        util.exportExcel(response, list, "【请填写功能名称】数据");
    }

    /**
     * 获取【请填写功能名称】详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:info:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(interfaceInfoService.selectInterfaceInfoById(id));
    }

    /**
     * 新增【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:info:add')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody InterfaceInfo interfaceInfo) {
        System.out.println(interfaceInfo.getUrl());
        return toAjax(interfaceInfoService.insertInterfaceInfo(interfaceInfo));
    }

    /**
     * 修改【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:info:edit')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody InterfaceInfo interfaceInfo) {
        return toAjax(interfaceInfoService.updateInterfaceInfo(interfaceInfo));
    }

    /**
     * 删除【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:info:remove')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(interfaceInfoService.logicDeleteCDlmUserByIds(ids));
    }


    /**
     * 发布【发布接口】
     */
    @PreAuthorize("@ss.hasPermi('system:info:online')")
    @PostMapping("/online/{id}")
    public AjaxResult onlineInterfaceInfo(@PathVariable("id") int id) {
        if (id <= 0) {
            throw new BaseException("InterfaceInfo", "400", null, "请求参数错误");
        }
        InterfaceInfo interfaceInfo = interfaceInfoService.selectInterfaceInfoById((long) id);
        if (interfaceInfo == null) {
            throw new BaseException("InterfaceInfo", "403", null, "拒绝请求");
        }
        com.donghu.openapiclientsdk.model.User user = new com.donghu.openapiclientsdk.model.User();
        user.setUsername("test");
        String username = openApiClient.getUsernameByPost(user);
        if (StringUtils.isBlank(username)) {
            throw new BaseException("InterfaceInfo", "403", null, "接口验证失败");
        }
        interfaceInfo.setStatus(InterfaceInfoStatus.ONLINE.getValue());
        interfaceInfoService.updateInterfaceInfo(interfaceInfo);
        return success("上线成功");

    }


    /**
     * 下线【下线接口】
     */

    @PreAuthorize("@ss.hasPermi('system:info:offline')")
    @PostMapping("/offline/{id}")
    public AjaxResult offlineInterfaceInfo(@PathVariable("id") Long id) {
//        System.out.println(interfaceInfo.getUrl());
//        return toAjax(interfaceInfoService.insertInterfaceInfo(interfaceInfo));
        if (id <= 0) {
            throw new BaseException("InterfaceInfo", "400", null, "请求参数错误");
        }
        InterfaceInfo interfaceInfo = interfaceInfoService.selectInterfaceInfoById(id);
        InterfaceInfo interfaceInfo1 = interfaceInfo;
        if (interfaceInfo1 == null) {
            throw new BaseException("InterfaceInfo", "403", null, "拒绝请求");
        }
        interfaceInfo.setStatus(InterfaceInfoStatus.OFFLINE.getValue());
        return toAjax(interfaceInfoService.updateInterfaceInfo(interfaceInfo));
    }


    /**
     * 测试 【测试接口】
     * <p>
     * 存在问题
     * 预期是等模拟接口调用完成，才记录响应日志，统计调用次数
     * 但现实是chain.filter方法立刻返回了，知道filter过滤器return后才调用模拟接口
     * 原因是：chain.filter是异步操作，理解为前端的promise
     */
    @PostMapping("/invoke")
    public AjaxResult InvokeInterfaceInfo(@RequestBody InterfaceInfoInvokeRequest interfaceInfoInvokeRequest, HttpServletRequest httpServletRequest) {
//        System.out.println(interfaceInfo.getUrl());
//        return toAjax(interfaceInfoService.insertInterfaceInfo(interfaceInfo));
        if (interfaceInfoInvokeRequest == null || interfaceInfoInvokeRequest.getId() <= 0) {
            throw new ServiceException("请求参数错误");
        }
        int id = interfaceInfoInvokeRequest.getId();
        String requestParams = interfaceInfoInvokeRequest.getRequestInvokeParams();
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.selectInterfaceInfoById((long) id);
        if (oldInterfaceInfo == null) {
            throw new ServiceException("没有该接口");
        }
        if (oldInterfaceInfo.getStatus() == InterfaceInfoStatus.OFFLINE.getValue()) {
            throw new ServiceException("接口关闭");
        }
//        String username = SecurityUtils.getUsername();
//        SysUser sysUser = sysUserService.selectUserByUserName(username);
////        userInterfaceInfoService.invokeCount(1L,1L);
//        String accessKey = sysUser.getAccessKey();
//        String secretKey = sysUser.getSecretKey();
//        User user = JSONUtil.toBean(requestParams, User.class);
//        OpenApiClient tempClient = new OpenApiClient(accessKey, secretKey);
//        String usernameByPost = tempClient.getUsernameByPost(user);
        String url = oldInterfaceInfo.getUrl();
        String method = oldInterfaceInfo.getMethod();
        String result = "";
        Boolean status = false;
        if (!requestParams.isEmpty()) {
            status = true;
        } else {
            status = false;
        }
        if (method.equals("GET") && status) {
            Map<String, Objects> params = JSON.parseObject(requestParams, Map.class);
            //将map转换为url参数 ？name=1&age=2 ？代表开始 &代表连接  =代表赋值 true代表转码 false代表不转码 一般不转码 会出现乱码 但是有些接口需要转码 例如百度的接口 需要转码 但是这里不需要转码 所以为false


            String query = MapUtil.join(params, "&", "=", true);
            String requestUrl=url+"?"+query;
            System.out.println(requestUrl);
            String s = HttpUtil.get(requestUrl);
            result = s;
        }
        if (method.equals("GET") && !status) {
            String s = HttpUtil.get(url);
            result = s;
        }
        if (method.equals("POST") && !status) {
            String s = HttpUtil.post(url, url);
            result = s;
        }
        if (method.equals("POST") && status) {
            Map<String, Objects> params = JSON.parseObject(requestParams, Map.class);
            String query = MapUtil.join(params, "&", "=", true);
            String requestUrl=url+"?"+query;
            System.out.println(requestUrl);
            String s = HttpUtil.post(requestUrl, requestUrl);
            result = s;
        }
        return AjaxResult.success(result);

    }





}
